package com.atguigu.juc1205.fileoperation;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Joey
 * @Date 2021/11/15 13:48
 * @Description
 */
public class OriginalWorkTime {

    public static void main(String[] args) throws JSONException {
        List<OriginalData> data = null;
        try {
            data = getData("D://xzq//公司/签卡数据 -2021.10.澳门北京原始.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //ctrl + alt + M 提炼函数的神级操作 快捷键提示工具，完事儿搜一下
        Map<String, List<OriginalData>> collect = getOriginalDataListGroupByName(data);


        JSONObject result = new JSONObject();
        for (String name : collect.keySet()) {
            List<OriginalData> dates = collect.get(name);
            Map<String, List<String>> collect1 = dates.stream().collect(
                    Collectors.groupingBy(OriginalData::getDate, Collectors.mapping(OriginalData::getSignTime, Collectors.toList())));
            result.put(name,optimization(collect1));
        }
        System.out.println(result);

    }

    private static Map<String, List<OriginalData>> getOriginalDataListGroupByName(List<OriginalData> data) {
        Map<String, List<OriginalData>> collect = data.stream().collect(Collectors.groupingBy(OriginalData::getName));
        return collect;
    }

    private static Map<String, List<String>>  optimization(Map<String, List<String>> collect1) throws JSONException {
        for (String date : collect1.keySet()) {
            List<String> dates1 = collect1.get(date);
            if (dates1.size() > 2){
                dates1.set(1,dates1.get(dates1.size()-1));
                for (int i = 2; i < dates1.size(); i++) {
                    dates1.remove(i);
                }
            }
            collect1.put(date,dates1);
        }
        return collect1;
    }

    static List<OriginalData> getData(String filePath) throws IOException, ParseException {
        List<OriginalData> result = new ArrayList<>(256);
        FileInputStream file = new FileInputStream(new File(filePath));
        HSSFSheet sheet = new HSSFWorkbook(file).getSheetAt(0);
        for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
            OriginalData originalData = new OriginalData();
            originalData.build(sheet.getRow(j));
            result.add(originalData);
        }
        return result;
    }

}
